/**
 * 观察应用是否关闭
 * 如果关闭则停止相关脚本
 */

let logger = require("./Logger");

module.exports = {
    watchOnClose
}

function watchOnClose(pkgName, interval) {
    logger.info(`[WatchApp] 开始检测 ${pkgName}`);
    let isRuning = isAppRunningWithRoot(pkgName);
    threads.start(() => {
        while (true) {
            logger.info(`[WatchApp] 检测 ${pkgName}`);
            try {
                if (!isRuning()) {
                    toast(`${pkgName} 已关闭，退出脚本`);
                    exit();
                }
            } catch (e) {
                logger.error("[WatchApp] 检测出错：" + e);
            }
            sleep(interval);
        }
    });
}

/**
 * pkg是否还在运行
 * 
 * 需要root权限
 * @param {string} pkg 
 * @returns 
 */
function isAppRunning(pkg) {
    let result = shell(`pidof ${pkg}`, true, 2000).result.trim();
    if (!result) {
        // 备用命令 ps
        result = shell(`ps | grep ${pkg}`, true, 2000).result.trim();
    }
    return !!result;
}

/**
 * pkg是否还在运行
 * 
 * 利用无障碍服务 判断前台app是否变动 变动就默认关闭了
 * 
 * 可能不准确
 * @param {string} pkg 
 */
function isAppRunningWithRoot(pkg) {
    let start = false;
    return function () {
        let currPkg = currentPackage();
        logger.info(`[WatchApp] 当前前台应用为 ${currPkg}`);
        if (!start && currPkg === pkg) {
            start = true;
        }
        if (!start) return true;
        let isOk = currPkg === pkg;
        logger.info(`[WatchApp] 前台应用是否变动 ${pkg} ${isOk ? "未变动" : "变动"}`);
        return isOk;
    }
}